package com.lill.org.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.lill.common.component.util.PageUtils;
import com.lill.common.component.util.Query;
import com.lill.common.component.util.R;
import com.lill.org.model.EmployeeModel;
import com.lill.org.service.IEmployeeService;
import com.lill.org.service.IPersonService;
import com.lill.support.annotation.CurrentUser;
import com.lill.system.model.SysUserEntity;
import com.lill.system.service.ICommonRedisService;

/**
 * 员工管理Controller
 *
 * @author lill
 * @date 2019-04-25 20:45:24
 */
@RestController
@RequestMapping("org/employeeInfo")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IPersonService personService;
    @Autowired
    private ICommonRedisService commonRedisService;

    /**
     * 查看列表
     */
    @RequestMapping("/list")
    //@RequiresPermissions("org:employeeInfo:list")
    public R list(@RequestParam Map<String, Object> params,@CurrentUser SysUserEntity user) {
    	if((null!=params&&!params.containsKey("companyId")) ||  params.get("companyId") == null || "".equals(params.get("companyId")+"")){
    		params.put("companyId", user.getCompanyId());
    	}
        //查询列表数据
        Query query = new Query(params);

        List<EmployeeModel> employeeList = employeeService.queryList(query);
        int total = employeeService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(employeeList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
    //@RequiresPermissions("org:employeeInfo:info")
    public R info(@PathVariable("id") String id) {
    	EmployeeModel employee = employeeService.queryObject(id);

        return R.ok().put("employee", employee);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    //@RequiresPermissions("org:employeeInfo:save")
    public R save(@RequestBody EmployeeModel employee,@CurrentUser SysUserEntity user) {
    	if(StringUtils.isNotEmpty(employee.getPhone())&&StringUtils.isNotEmpty(employee.getName())){
    		Map<String, Object> mapQuery=new HashMap<String, Object>();
    		mapQuery.put("phone", employee.getPhone());
    		List<Map<String, Object>> list = employeeService.queryPersonList(mapQuery);
    		if(null!=list&&!list.isEmpty()){
    			if(employee.getPhone().equals(list.get(0).get("phone").toString())
    					&&employee.getName().equals(list.get(0).get("name").toString())){
    				boolean result=true;
    				for (int i = 0; i < list.size(); i++) {
						if(employee.getCompanyId().equals(list.get(i).get("company_id"))){
							result=false;break;
						}
					}
    				if(result){
    					employee.setPersonId(list.get(0).get("id").toString());
    				}else{
    					if(StringUtils.isNotEmpty(employee.getPhoneCode())){
    						String code=commonRedisService.getStringValueByKey(ICommonRedisService.phoneCode+employee.getPhone());
    						if(!code.equals(employee.getPhoneCode())){
    							return R.error(1, "手机号已经被使用，手机验证码有误！");
    						}
    					}else{
    						return R.error(1, "手机号已经被使用！");
    					}
    				}
    			}
    		}
    	}
    	
    	employee.setStatus(1);
    	employee.setCreateUser(user.getId());
    	employee.setCreateTime(new Date());
        int result=employeeService.save(employee);
		if(result>0){
        	return R.ok();
        }else{
        	return R.failure();
        }
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    //@RequiresPermissions("org:employeeInfo:update")
    public R update(@RequestBody EmployeeModel employee,@CurrentUser SysUserEntity user) {
    	if(null!=employee.getPhone()&&!"".equals(employee.getPhone())){
    		EmployeeModel employeeOld=employeeService.queryObject(employee.getId());
    		if(StringUtils.isNotEmpty(employeeOld.getPhone())&&employeeOld.getPhone().equals(employee.getPhone())){
    		}else{
    			Map<String, Object> mapQuery=new HashMap<String, Object>();
        		mapQuery.put("phone", employee.getPhone());
        		int num=personService.queryTotal(mapQuery);
        		if(num>0){
        			if(StringUtils.isNotEmpty(employee.getPhoneCode())){
        				String code=commonRedisService.getStringValueByKey(ICommonRedisService.phoneCode+employee.getPhone());
        				if(StringUtils.isEmpty(code)||!code.equals(employee.getPhoneCode())){
        					return R.error(1, "手机号已经被使用！验证码有误！");
        				}
        			}else{
        				return R.error(1, "手机号已经被使用！");
        			}
        		}
    		}
    	}
    	employee.setUpdateUser(user.getId());
    	employee.setUpdateTime(new Date());
        int result=employeeService.update(employee);
		if(result>0){
        	return R.ok();
        }else{
        	return R.failure();
        }
    }
    
    @RequestMapping("/password")
    //@RequiresPermissions("org:employeeInfo:update")
    public R updatePassword(@RequestBody Map<String, Object> mapParam,@CurrentUser SysUserEntity user) {
    	if(null!=mapParam&&!mapParam.isEmpty()&&null!=mapParam.get("newPassword")&&!"".equals(mapParam.get("newPassword").toString())){
    		mapParam.put("newPassword",new Sha256Hash(mapParam.get("newPassword").toString()).toHex());
    	}
    	mapParam.put("updateUser",user.getId());
    	mapParam.put("updateTime",new Date());
    	int result=employeeService.updatePassword(mapParam);
    	if(result>0){
    		return R.ok();
    	}else{
    		return R.failure();
    	}
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    //@RequiresPermissions("org:employeeInfo:delete")
    public R delete(@RequestBody String[] ids,@CurrentUser SysUserEntity user) {
    	Map<String, Object> params=new HashMap<String, Object>();
    	params.put("ids", ids);
    	params.put("updateUser", user.getId());
    	params.put("updateTime", new Date());
    	
        int result=employeeService.deleteLogicByMap(params);
		if(result>0){
        	return R.ok();
        }else{
        	return R.failure();
        }
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    public R queryAll(@RequestParam Map<String, Object> params) {
        List<EmployeeModel> list = employeeService.queryList(params);
        return R.ok().put("list", list);
    }
    
    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAllPerson")
    public R queryAllPerson(@RequestParam Map<String, Object> params) {
    	if(null!=params&&!params.isEmpty()&&params.containsKey("phone")&&StringUtils.isNotEmpty(params.get("phone").toString())){
    		String code=commonRedisService.getStringValueByKey(ICommonRedisService.phoneCode+params.get("phone").toString());
    		if(StringUtils.isNotEmpty(code)){
    			return R.ok().put("list", new ArrayList<Object>());
    		}
    	}
    	List<Map<String, Object>> list = employeeService.queryPersonList(params);
    	return R.ok().put("list", list);
    }


	@RequestMapping("/employees")
	public R employeeList(@RequestParam Map<String, Object> params) {

		Object departIdsObj = params.get("departIds");
		String departIdsStr=null;
		String[] departIds=null;
		if(null!=departIdsObj){
			departIdsStr=departIdsObj.toString().replaceAll("\"","").replaceAll("]","").trim();
			departIds = departIdsStr.split(",");
		}

		params.put("departIds",departIds);
		//查询列表数据
		Query query = new Query(params);

		List<EmployeeModel> employeeList = employeeService.queryEmployeeList(query);
		int total = employeeService.queryTotal(query);
		if(StringUtils.isEmpty(departIdsStr)){
			employeeList=null;
			total=0;
		}
		PageUtils pageUtil = new PageUtils(employeeList, total, query.getLimit(), query.getPage());

		return R.ok().put("page", pageUtil);
	}
	/**
	 * 查看所有列表
	 */
	@RequestMapping("/queryAtherPerson")
	public R queryAtherPerson(@RequestParam Map<String, Object> params) {
		if(null!=params&&!params.isEmpty()&&params.containsKey("phone")&&StringUtils.isNotEmpty(params.get("phone").toString())){
			String code=commonRedisService.getStringValueByKey(ICommonRedisService.phoneCode+params.get("phone").toString());
			if(StringUtils.isNotEmpty(code)){
				return R.ok().put("list", new ArrayList<Object>());
			}
		}
		List<Map<String, Object>> list = employeeService.queryPersonOhterList(params);
		return R.ok().put("list", list);
	}
}
